package com.roc.web.action.estrn;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.DayStastics;
import com.roc.pojo.Operators;
import com.roc.pojo.TblTfrTrnLog;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
 * 日报表
 * @author 160711BB
 *
 */
@Component
@Scope("prototype")
@Namespace("/day")
public class DayStasticsAction extends PaginationBaseAction{
	private DayStasticsSearchCondition searchCondition;
	
	private Logger logger=LogManager.getLogger(DayStasticsAction.class);
	private InputStream excelFile;
	
	@Autowired
	IPageService pagenitionService;
	
	@Autowired
	private IPowerInfoService powerInfoService;
	
	@Autowired
	IExcelService excelService;
	
	@Action(value = "queryDayStasticInit", results = { @Result(name = "success", location = "/pages/estrn/dayStastic.jsp")
    })
	public String queryDayStasticInit(){
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (!Role.O_MANAGER.getCode().equals(logingMerchant.getRoleType())
				&& !Role.OPERATORS_COMM.getCode().equals(
						logingMerchant.getRoleType())
				&& !Role.SYSTEM.getCode().equals(logingMerchant.getRoleType()) && !Role.OPERATORS_LEAD.getCode().equals(logingMerchant.getRoleType())) {
			addActionError("无权限访问!!!");
			return ERROR;
		}
		return SUCCESS;
	}
	
	
	@Action(value = "queryDayStasticsList", results = { @Result(name = "success", location = "/pages/estrn/dayStastic.jsp")
    })
	public String queryDayStasticsList(){
		try {
			
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			
			if(searchCondition==null){
				searchCondition=(DayStasticsSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new DayStasticsSearchCondition();
				}
			}
			
			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
			String superRole= map.get("superRole");
			String opRealId =map.get("opRealId");
			searchCondition.setRoleType(superRole);
			if(Role.O_MANAGER.getCode().equals(superRole)){
				
				String agentId= opRealId;
				searchCondition.setAgentId(agentId);
					
			}else if(Role.AGENT.getCode().equals(superRole)){
				addActionError("无权限访问!!!");
				return ERROR;
			}
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<DayStastics> staList = new ArrayList<DayStastics>();
			dealTheSearchRsList(staList,searchRsList,searchCondition.getMinDate(),searchCondition.getMaxDate());
		
			getRequest().setAttribute("staList", staList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	
	@Action(value="exportDayStasticsList",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/estrn/dayStastic.jsp") }) 
	public String  exportDayStasticsList() throws Exception{
		try {
			
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			
			if(searchCondition==null){
				searchCondition=(DayStasticsSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new DayStasticsSearchCondition();
				}
			}
			
			Map<String, String> map=powerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
			String superRole= map.get("superRole");
			String opRealId =map.get("opRealId");
			searchCondition.setRoleType(superRole);
			if(Role.O_MANAGER.getCode().equals(superRole)){
				
				String agentId= opRealId;
				searchCondition.setAgentId(agentId);
					
			}
			
			
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<DayStastics> staList = new ArrayList<DayStastics>();
			Map<String,String> resMap = dealTheSearchRsList(staList,searchRsList, searchCondition.getMinDate(), searchCondition.getMaxDate());
		
			SXSSFWorkbook  work=excelService.exportDayStasticsList(staList,searchCondition.getMinDate(),searchCondition.getMaxDate(),resMap);

			ByteArrayOutputStream output = new ByteArrayOutputStream();  
			work.write(output);  
			byte[] ba = output.toByteArray();  
			excelFile = new ByteArrayInputStream(ba);  
			output.flush();  
			output.close();  
			
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		return SUCCESS;
	}
	
	
	private Map<String,String> dealTheSearchRsList(List<DayStastics> staList,
			List<Object> searchRsList, String minDate, String maxDate) {
		BigDecimal totalTransAmt = new BigDecimal(0);
		BigDecimal totalFee = new BigDecimal(0);
		BigDecimal totalCount = new BigDecimal(0);
		BigDecimal totalIncome = new BigDecimal(0);
		Map<String,String> resMap = new HashMap<String, String>();
		try {
	    
		if(searchRsList!=null&&searchRsList.size()>0){
			Iterator iterator=searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				DayStastics pojo = new DayStastics();
				
				pojo.setTransDt(minDate+"-"+maxDate);
				pojo.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
				pojo.setTermId(Constance.Null2EmptyTrim(obj[1]));
				pojo.setNameBusi(Constance.Null2EmptyTrim(obj[2]));
				pojo.setProvName(ConfigMerinfoUtil.getGBProviceName(Constance.Null2EmptyTrim(obj[3])));
				pojo.setCityName(ConfigMerinfoUtil.getGBCityName(Constance.Null2EmptyTrim(obj[4])));
				pojo.setUpMccCd(Constance.Null2EmptyTrim(obj[5]));
				pojo.setMccSuperName(Constance.Null2EmptyTrim(obj[6]));
				
				pojo.setOrgName(Constance.Null2EmptyTrim(obj[7]));
				pojo.setCompanyName(Constance.Null2EmptyTrim(obj[8]));
				pojo.setTotalCount(Constance.Null2EmptyTrim(obj[9]));
				pojo.setTotalAmt(Constance.Null2EmptyTrim(obj[10]));
				pojo.setMchtFee(Constance.Null2EmptyTrim(obj[11]));
				String income = Constance.Null2EmptyTrim(obj[12]);
				if(Double.parseDouble(income)<0){
					pojo.setInCome("0.00");
				}else{
					pojo.setInCome(income);
				}
				
				pojo.setRealName(Constance.Null2EmptyTrim(obj[13]));
				
				totalTransAmt = totalTransAmt.add(new BigDecimal(pojo.getTotalAmt()));
				totalCount = totalCount.add(new BigDecimal(pojo.getTotalCount()));
				totalFee = totalFee.add(new BigDecimal(pojo.getMchtFee()));
				totalIncome = totalIncome.add(new BigDecimal(pojo.getInCome()));
				
				staList.add(pojo);
				
			}
		}
		
		//
		resMap.put("totalTransAmt", totalTransAmt.toPlainString());
		resMap.put("totalCount", totalCount.toPlainString());
		resMap.put("totalFee", totalFee.toPlainString());
		resMap.put("totalIncome", totalIncome.toPlainString());
		
		} catch (Exception e) {
			logger.error("日报表数据解析异常",e);
			throw new RuntimeException("日报表数据解析异常");
		}
		
		return resMap;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_DAY_STASTICS, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (DayStasticsSearchCondition)getSession().getAttribute(SEARCH_SESSION_DAY_STASTICS);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}
	
	public String getExcelName() {
		String excelName="日报表"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}

	public DayStasticsSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(DayStasticsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

}
